<?php

abstract class Domain51_Controller_Locator extends Solar_Base
{
    
    public function __construct($config = null) {
        parent::__construct($config);
        
        $exploded = explode('_', get_class($this));
        while ($prefix = array_pop($exploded)) {
            if ($prefix != 'Locator') {
                break;
            }
        }
    }
    
    public function locate($uri = null) 
    {
        // we need to make a copy of $uri->path as we might not find it. 
        $path = $uri->path;
        
        // pull the page name off the top of the path, use the default
        // if none specified
        $page = array_shift($path);
        
        if (trim($page) == '') {
            $page = $this->_default;
        }
        
        // convert from "pageName, page-name, page_name" to "PageName"
        $page = str_replace(array('_', '-'), ' ', $page);
        $page = str_replace(' ', '', ucwords(trim($page)));
        
        // does the page map to a known class?
        foreach (array_reverse($this->_config['prefixes']) as $base) {
            
            // get a class name
            $class = '';
            
            // allow for empty namespaces
            if (!empty($base)) {
                $class .= $base . '_';
            }
            
            $class .= $page . '_Controller';
            
            // attempt to load class - catch not-found exception
            try {
                $class = Solar::loadClass($class);
                
                // now that we found something, shift it off of the beginning of
                // $uri->path array and stop
                array_shift($uri->path);
                break;
                
            } catch (Exception $e) {
                if ($e->getCode() !== 'ERR_FILE_NOT_READABLE') {
                    throw $e;
                }
            }
            // not found at all.
            $class = false;
        }
        
        // did we find the page class?
        if (! $class) {
            return false;
        }
        
        // instantiate the controller and return it
        return Solar::factory($class, $this->_config);
    }
}

?>